package com.hankol.community.viewmodel

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.RelativeLayout
import androidx.lifecycle.MutableLiveData
import com.baselibrary.Constants
import com.baselibrary.adapter.LocusImagePageAdapter
import com.baselibrary.activity.BaseActivity
import com.baselibrary.base.mvvm.BaseViewModel
import com.baselibrary.bean.CommentEnum
import com.baselibrary.bean.ShareItemBean
import com.baselibrary.bean.SharePosterBean
import com.baselibrary.extension.checkNotNull
import com.baselibrary.extension.checkValue
import com.baselibrary.manager.LoadingManager
import com.baselibrary.manager.SensorsDataManager
import com.baselibrary.permission.PermissionCollection
import com.baselibrary.permission.PermissionsUtils
import com.baselibrary.permission.callback.PermissionsCall
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.*
import com.baselibrary.view.share.SharePopupWindow
import com.hankol.community.R
import com.hankol.community.SelectFriendShareActivity
import com.hankol.community.ShareFriendActivity
import com.hankol.community.arouter.CommunityHelp
import com.hankol.community.bean.ShowShare2Bean
import com.baselibrary.bean.TimelineInfoData
import com.hankol.community.bean.clientTimeline2SelectSendFriend2Bean
import com.hankol.community.bean.showShare2Bean2SelectSendFriend2Bean
import com.hankol.community.databinding.ActivityPictureDetailsBinding
import com.hankol.community.respository.CommunityRequestManager
import com.okhttp.comment.CommentBean

/**
 * @author: 关忆北、
 * @date: 2022/3/24
 * @Des：
 */
class PictureDetailsViewModel : BaseViewModel() {
    lateinit var mDataBinding: ActivityPictureDetailsBinding
    var commentListLiveData: MutableLiveData<CommentBean.DataBean> = MutableLiveData()
    var dynamicLiveData: MutableLiveData<TimelineInfoData.ClientTimeline> = MutableLiveData()
    fun reqCommentList(page: Int, pictureId: Long, topCommentId: Long) {
        CommunityRequestManager.getInstance().reqCommentList(commentListLiveData, page, CommentEnum.COMMENT_DYNAMIC.commentType, pictureId, 0, topCommentId)
    }

    fun reqDynamicDetails(dynamicId: Long) {
        CommunityRequestManager.getInstance().reqDynamicDetails(dynamicLiveData, dynamicId)
    }


    fun initView(it: TimelineInfoData.ClientTimeline, activity: Activity) {
        if (SpUtils.getInstance().isLogin) {
            mDataBinding.llPictureDetComment.visibility = View.VISIBLE
            SpUtils.getInstance().loadUserBean.data?.let {
                mDataBinding.circlePictureDetCurrentHead.setData(it.icon.checkValue(), it.isFans == 1, View.GONE)
            }
        } else {
            mDataBinding.llPictureDetComment.visibility = View.GONE
        }
        mDataBinding.vipPictureDetHead.setData(it.user.icon, it.user.isFans == 1)
        mDataBinding.tvPictureDetName.text = it.user.name
        mDataBinding.tvPictureDetTime.text = TimeUtil.fromToday(it.ctime)
        if (it.address.checkNotNull()) {
            mDataBinding.tvPictureDetLocation.visibility = View.VISIBLE
            mDataBinding.tvPictureDetLocation.text = it.address
        } else {
            mDataBinding.tvPictureDetLocation.visibility = View.GONE
        }
        if (it.user.id == SpUtils.getInstance().userId) {
            //自己发布的动态
            mDataBinding.ivPictureDetFollow.visibility = View.GONE
        } else {
            mDataBinding.ivPictureDetFollow.visibility = View.VISIBLE
            mDataBinding.ivPictureDetFollow.isSelected = it.user.isFocusFans
            mDataBinding.ivPictureDetFollow.setImageResource(if (it.user.isFocusFans) R.drawable.ic_picture_true_follow else R.drawable.ic_picture_flase_follow)
        }
        if (it.address.checkNotNull()) {
            mDataBinding.tvPictureDetName.textSize = 14f
            mDataBinding.tvPictureDetLocation.text = it.address
            mDataBinding.llPictureDetLocation.visibility = View.VISIBLE
        } else {
            mDataBinding.llPictureDetLocation.visibility = View.GONE
        }

        if (it.tags.checkNotNull()) {
            mDataBinding.tvPictureDetTopic.visibility = View.VISIBLE
            mDataBinding.tvPictureDetTopic.text = "# ${it.tags[0]}"
        } else {
            mDataBinding.tvPictureDetTopic.visibility = View.GONE
        }
        if (it.content.checkNotNull()) {
            mDataBinding.tvPictureDetDes.paint.isFakeBoldText = true
            mDataBinding.tvPictureDetDes.visibility = View.VISIBLE
            mDataBinding.tvPictureDetDes.text = it.content
        } else {
            mDataBinding.tvPictureDetDes.visibility = View.GONE
        }

        if (it.images.checkNotNull()) {
            val maxHeight = getMaxHeight(it, activity)
            mDataBinding.tvPictureDetIndex.visibility = View.VISIBLE
            mDataBinding.tvPictureDetIndex.text = "${1}/${it.images.size}"
            mDataBinding.vpPictureDetPicture.adapter = LocusImagePageAdapter(it.images, maxHeight, activity)

            if (it.images.size >= 2) {
                //底部指示器
                mDataBinding.indicatorPicture.setSumCount(it.images.size)
            }
            upCollectionSate(it)
            upSupportSate(it)
        }
    }

    fun getMaxHeight(data: TimelineInfoData.ClientTimeline, activity: Activity): Int {
        //已经取消了最大高的计算
        val viewHeight = ScreenUtils.getVideoHight(data.images[0]).toInt()
        val viewWidth = ScreenUtils.getVideoWidth(data.images[0]).toInt()
        val measureViewHWArray = ScreenUtils.measureViewHW(activity, viewHeight.toFloat(), viewWidth.toFloat(), Constants.DYNAMIC_PICTURE_SCALE, ScreenUtils.dip2px(activity, 28f))
        val layoutParams: RelativeLayout.LayoutParams = mDataBinding.vpPictureDetPicture.layoutParams as RelativeLayout.LayoutParams
        layoutParams.width = measureViewHWArray[0]
        layoutParams.height = measureViewHWArray[1]
        mDataBinding.vpPictureDetPicture.layoutParams = layoutParams
        return 0;
    }

    /**
     * 更新收藏状态
     */
    fun upCollectionSate(it: TimelineInfoData.ClientTimeline) {
        mDataBinding.includeCommentView.tvCommentConCount.text = if (it.favoriteNum == 0) "收藏" else NumberUtils.formatBigNum(it.favoriteNum.toString())
        mDataBinding.includeCommentView.llCommentCollection.isSelected = it.isFavorited
        mDataBinding.includeCommentView.ivCommentConState.isLiked = it.isFavorited
    }

    /**
     * 更新点赞状态
     */
    fun upSupportSate(it: TimelineInfoData.ClientTimeline) {
        mDataBinding.includeCommentView.tvCommentGiveCount.text = if (it.supportNum == 0) "点赞" else NumberUtils.formatBigNum(it.supportNum.toString())

        mDataBinding.includeCommentView.ivCommentGiveState.isLiked = it.isSupported
        mDataBinding.includeCommentView.llCommentGive.isSelected = it.isSupported
    }


    fun showShare(dynamicData: TimelineInfoData.ClientTimeline, activity: BaseActivity, communityHelp: CommunityHelp): SharePopupWindow? {
        val data = pulCourseBean2showShare(dynamicData)
        val title = if (data.content.checkNotNull()) data.content else "@${data.name}发了一个动态，快点开来看看！"
        val des = if (data.content.checkNotNull()) data.content else ""
        val shareItem = ShareManager.showSharePopWindow(activity, data.url, data.cover, title, des, object : SharePopupWindow.OnShareClickListener {

            override fun onShareClick(type: Int) {
                when (type) {
                    ShareItemBean.WXZone, ShareItemBean.WX -> {
                        reqAddShareNum(dynamicData.id)
                    }
                    ShareItemBean.DOWN -> {

                    }
                    ShareItemBean.POSTER -> {
                        PermissionsUtils.getInstance().chekPermissions(activity, PermissionCollection.FILE.permissionList, object : PermissionsCall() {
                            override fun permissionsPass() {
                                LoadingManager.showLoadingDialog(activity)
                                var sharePosterBean: SharePosterBean = changePosterBean(dynamicData)
                                sharePosterBean.imagePaths = ArrayList()
                                for (i in 0..2) {
                                    val posterStyle = PosterStyle(activity, sharePosterBean, i) { path: String? ->
                                        sharePosterBean.imagePaths.add(path)
                                        checkListSize(activity, sharePosterBean)
                                    }
                                    posterStyle.startDraw()
                                }
                            }
                        })
                    }
                    ShareItemBean.REPORT -> {
                        val intent = Intent()
                        val bundle = Bundle()
                        bundle.putInt("type", 3)
                        bundle.putInt("id", data.id.toInt())
                        bundle.putInt("complaintUserId", data.uid.toInt())
                        intent.putExtras(bundle)
                        activity.openActivity(communityHelp.getJuBaoOneActivity(), bundle)

                    }
                }
            }

            override fun onShareFriendClick(bean: ShareItemBean) {
                if (bean.userId == 0L) {//私信
                    val intent = Intent(activity, SelectFriendShareActivity::class.java)
                    intent.putExtra("friend", bean)
                    intent.putExtra("dynamic", clientTimeline2SelectSendFriend2Bean(dynamicData))
                    activity.startActivity(intent)
                } else {
                    val intent = Intent(activity, ShareFriendActivity::class.java)
                    intent.putExtra("friend", bean)
                    intent.putExtra("dynamic", showShare2Bean2SelectSendFriend2Bean(data))
                    activity.startActivity(intent)
                }

            }
        })
        shareItem?.setShareItem(true, false, true);
        return shareItem
    }

    fun checkListSize(activity: Activity, sharePosterBean: SharePosterBean) {
        if (sharePosterBean.imagePaths.size == 3) {
            LoadingManager.hideLoadingDialog(activity)
            val bundle = Bundle()
            bundle.putSerializable(Constants.SHARE_POSTER_BEAN, sharePosterBean)
            ActivityRouter.startActivity(ActivityRouter.ACTIVITY.SHARE_POSTER_SELECT, bundle)
        }
    }

    fun pulCourseBean2showShare(bean: TimelineInfoData.ClientTimeline): ShowShare2Bean {
        return ShowShare2Bean().apply {
            id = bean.id
            uid = bean.user.id
            isFans = bean.user.isFans
            headUrl = bean.user.icon
            showType = Constants.DYNAMIC_TYPE_IMG
            name = bean.user.name
            cover = bean.cover
            title = bean.title
            content = bean.content
            url = Constants.DYNAMIC_SHARE_URL + bean.id
        }
    }

    fun changePosterBean(data: TimelineInfoData.ClientTimeline): SharePosterBean {

        val sharePosterBean = SharePosterBean(2)
        sharePosterBean.userAvatar = data.user.icon
        sharePosterBean.userName = data.user.name
        sharePosterBean.shareImage = data.images[0]
        sharePosterBean.shareContent = data.content
        sharePosterBean.atPersonName = getStrAt(data.atMembers)
        sharePosterBean.isVideo = data.showType == 2
        sharePosterBean.isFans = data.user.isFans == 1
        sharePosterBean.isWinnery = data.user.isWinery != 0
        return sharePosterBean
    }

    /**
     * 将艾特的人名拼接成字符串
     */
    fun getStrAt(atMembers: List<TimelineInfoData.AtMembersBean>): String {
        if (atMembers.isEmpty()) return ""
        val mBuffer = StringBuffer()
        for (atMember in atMembers) {
            mBuffer.append("@" + atMember.name).append("  ")
        }
        return mBuffer.toString()
    }

    fun sensors(mDataBean: TimelineInfoData.ClientTimeline?, sourceName: String) {
        mDataBean?.let {
            if (SensorsDataManager.instance.getBrowseTime() != 0L) {
                SensorsDataManager.instance.browseDynamic(it.tagCategoryName, sourceName, subString(it.title), getStateType(it.recommendType), "图片动态", if (it.tags.checkNotNull()) it.tags[0] else "", 0)
                if (it.wineryCode != 0L) {//酒窖发布的动态
                    SensorsDataManager.instance.cellarDynamicSee(it.wineryName.checkValue())
                }
            }
        }
    }


    fun subString(content: String): String {
        if (!content.checkNotNull()) return ""
        if (content.length > 12) {
            return content.substring(0, 12)
        }
        return content
    }

    private fun getStateType(remark: Int): String {
        return when (remark) {
            TimelineInfoData.ClientTimeline.RECOMMEND_TYPE -> {
                "推荐动态"
            }
            TimelineInfoData.ClientTimeline.TOPPING_TYPE -> "置顶动态"
            else -> {
                "普通动态"
            }
        }
    }
}